package com.hdy.javachatroomdemo.Config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.ObjectId;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;

import com.aliyun.oss.internal.model.OSSErrorResult;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.hdy.javachatroomdemo.Enum.ResultCodeEnum;
import com.hdy.javachatroomdemo.Model.OSSResult;
import com.hdy.javachatroomdemo.constant.Constants;
import com.hdy.javachatroomdemo.exception.ServiceException;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class OSSService {
    @Autowired
    private OSSProperties ossProperties;
    @Autowired
    private OSS ossClient;
    @SneakyThrows
    public OSSResult uploadFile(MultipartFile file){
        String fileName=file.getOriginalFilename();
        if(StringUtils.hasText(fileName)){
            fileName=fileName.toLowerCase();
        }else{
            fileName= Constants.DEFAULT_FILE_NAME;
        }
        String ext=fileName.substring(fileName.lastIndexOf(".")+1);
        OSSResult ossResult=upload(ext,file);
        return ossResult;
    }

    private OSSResult upload(String ext, MultipartFile file) throws IOException {
        String fileName= ossProperties.getPath()+ ObjectId.next()+"."+ext;
        PutObjectResult putObjectResult;
        try(InputStream inputStream = file.getInputStream() ){
            PutObjectRequest putObjectRequest=new PutObjectRequest(ossProperties.getBucketName(),fileName,inputStream);
            putObjectResult = ossClient.putObject(putObjectRequest);
        } catch (Exception e) {
            throw new ServiceException(ResultCodeEnum.FAIL_UPLOAD_FILE);
        }
        OSSResult ossResult=assembleOSSResult(putObjectResult,fileName);
        return ossResult;
    }

    private OSSResult assembleOSSResult(PutObjectResult putObjectResult, String fileName) {
        OSSResult ossResult=new OSSResult();
        if(putObjectResult==null||!StringUtils.hasText(putObjectResult.getRequestId())){
            ossResult.setSuccess(Boolean.FALSE);
        }else{
            ossResult.setSuccess(Boolean.TRUE);
            ossResult.setFileName(FileUtil.getName(fileName));
        }
        return ossResult;
    }
}
